import sys
import os
import aiohttp
import asyncio
import ujson
from properties_handler import Properties

config_base_path = os.path.dirname(__file__)
properties = Properties(os.path.join(config_base_path, "config.properties")).get_properties()
server_base_url = properties.get("client.remote-base-url")
key = properties.get("client.key")
ipcheck_url = properties.get("client.ipcheck-url")
ipv6check_url = properties.get("client.ipv6check-url")
mac_address = properties.get("client.mac")

user_properties = Properties(os.path.join(config_base_path, "config-user.properties")).get_properties()
custom_server_base_url = user_properties.get("client.remote-base-url")
custom_key = user_properties.get("client.key")
custom_ipcheck_url = user_properties.get("client.ipcheck-url")
custom_ipv6check_url = user_properties.get("client.ipv6check-url")
custom_mac_address = user_properties.get("client.mac")

if custom_server_base_url is not None:
    server_base_url = custom_server_base_url
if custom_key is not None:
    key = custom_key
if custom_ipcheck_url is not None:
    ipcheck_url = custom_ipcheck_url
if custom_ipv6check_url is not None:
    ipv6check_url = custom_ipv6check_url
if custom_mac_address is not None:
    mac_address = custom_mac_address

if key is None or key == "":
    print("请先在config-user.properties中设置client.key")
    sys.exit(0)


async def get_ipv6():
    pass


async def main():
    while True:
        try:
            session = aiohttp.ClientSession(json_serialize=ujson.dumps)
            resp = await session.get(ipcheck_url)
            ip = await resp.text()

            resp = await session.get(ipv6check_url)
            ipv6 = await resp.text()

            body = {
                "key": key,
                "ip": ip,
                "ipv6": ipv6,
                "mac": mac_address
            }
            resp = await session.post(server_base_url + '/set-ip', json=body)
            print(await resp.json())
            await session.close()
        except Exception as exp:
            print("网络异常")

        await asyncio.sleep(60)


if __name__ == '__main__':
    try:
        asyncio.run(main())
    except Exception as error:
        loop = asyncio.get_event_loop()
        tasks = [main()]
        loop.run_until_complete(asyncio.gather(*tasks))
